""" 4 SD卡：使用SD卡存储数据 """
# https://learn.adafruit.com/adafruit-microsd-card-bff
# https://learn.adafruit.com/adafruit-microsd-spi-sdio/circuitpython

import board
import storage
import digitalio
import adafruit_sdcard
import os

print("start")
spi = board.SPI()
cs = digitalio.DigitalInOut(board.A5)

print("connect")
sdcard = adafruit_sdcard.SDCard(spi, cs)

print("VfsFat")
vfs = storage.VfsFat(sdcard)

print("mount")
storage.mount(vfs, "/sd")
print("mount ok")

print("write")
with open("/sd/test.txt", "w") as f:
    f.write("Hello world!\r\n")
    f.write("I'am circuitpython!\r\n")

print("read")
with open("/sd/test.txt", "r") as f:
    print("Printing lines in file:")
    for line in f:
        print(line, end='')

print("Dir: /sd")
dir = os.listdir('/sd')
for i in dir:
    print(i)

storage.umount("/sd")
print("end")
